package cn.qidisoft.edu.hzjt.controller.zyc;

import cn.qidisoft.core.common.log.LoggerAdapter;
import cn.qidisoft.core.common.log.LoggerAdapterFactory;
import cn.qidisoft.core.common.pagination.Page;
import cn.qidisoft.core.common.pagination.PaginationBean;
import cn.qidisoft.core.util.moffice.excel.ExpExcelUtil;
import cn.qidisoft.core.web.customargument.bind.annotation.Token;
import cn.qidisoft.edu.hzjt.controller.BaseController;
import cn.qidisoft.edu.hzjt.exception.RPCException;
import cn.qidisoft.edu.hzjt.model.Employee;
import cn.qidisoft.edu.hzjt.model.ResponseResult;
import cn.qidisoft.edu.hzjt.model.zyc.PartyBranch;
import cn.qidisoft.edu.hzjt.model.zyc.PartyCommitteeMember;
import cn.qidisoft.edu.hzjt.model.zyc.PartyLeagueMember;
import cn.qidisoft.edu.hzjt.service.zyc.IDzbService;
import cn.qidisoft.edu.hzjt.service.zyc.IEmpService;
import cn.qidisoft.edu.hzjt.utils.LogType;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 党支部管理
 * 
 * @author zhangwenliang
 * @date 2018.11.13
 */
@Controller
@RequestMapping("/dzb/")
public class DzbController {
	protected static final LoggerAdapter LOGGER = LoggerAdapterFactory.getLogger(LogType.HZJT_LOGGER.val);
	@Autowired
	private IEmpService empService;

	@Autowired
	private IDzbService dzbService;
	
	private int zBID;
	/**
	 * 跳转到列表页面
	 * 
	 * @return
	 */
	@RequestMapping("list")
	public String list() {
		return "zyc/dzb/list";
	}

	/***
	 * 获取列表分页数据
	 * 
	 * @param model
	 * @param request
	 * @param pageSize
	 * @param currentPage
	 * @param student
	 * @return
	 */
	@RequestMapping("getListData")
	@ResponseBody
	public ResponseResult getListData(ModelMap model, HttpServletRequest request,
			@RequestParam(value = "rows", required = false) String pageSize,
			@RequestParam(value = "page", required = false) String currentPage, PartyBranch partyBranch) {
		System.out.println(pageSize + currentPage);
		Page page = new Page();
		page.setCurrPage(currentPage == null ? 0 : Integer.valueOf(currentPage));
		page.setPageSize(pageSize == null ? 10 : Integer.valueOf(pageSize));
		BaseController.setSortByColumn(request, "cLRQ", "desc");
		Map<String, Object> queryMap = new HashMap<String, Object>();
		String dZBMC = request.getParameter("dZBMC");
		if(null != dZBMC) {
			queryMap.put("dZBMC", dZBMC.trim());
		}
		queryMap.put("orderField", (String) request.getAttribute("orderField"));
		queryMap.put("orderFlag", (String) request.getAttribute("orderFlag"));
		System.out.println(queryMap.get("orderField")+ "vvvvvvvv");
		System.out.println(queryMap.get("orderFlag") + "ssssssssss");
		PaginationBean<PartyBranch> paginationBean = dzbService.getListData(queryMap, page);
		ResponseResult result = new ResponseResult();
		result.setTotal(paginationBean.getTotalRecords());
		result.setRows(paginationBean.getPageList());
		return result;
	}

	/**
	 * 跳转到添加页面
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "add")
	@Token(save = true)
	public String add(ModelMap model, HttpServletRequest request) {
		try {
			List<Employee> employees = empService.getDmplist();
			request.setAttribute("employees", employees);
		} catch (Exception e) {
			LOGGER.error("获得xxxxx信息 addStudentDemoForward [{}] error," + this.getClass().getName() + "=[{}]",
					this.getClass().getName(), e.getMessage());
			return "error/error";
		}
		return "zyc/dzb/add";
	}
	
	/**
	 * 保存党支部信息
	 * @param model
	 * @param request
	 * @return 3）保存时，对党支部书记和委员，判断是否在党员信息中，没有，则自动加入党员表
	 */
	@RequestMapping(value = "insert")
	public String insert(ModelMap model, HttpServletRequest request, PartyBranch partyBranch) {
		String dZBWY_NAME = null;
		String dZBWY = null;
		try {
			//添加党支部信息
			partyBranch.setgID("");
			dzbService.addDzbinfo(partyBranch);
		    zBID = partyBranch.getzBID();
			if (zBID > 0) {
				
				List<Integer> empIds  = new ArrayList<Integer>();
				
				//插入委员信息表
				List<PartyCommitteeMember> list = new ArrayList<PartyCommitteeMember>();
			    dZBWY = request.getParameter("wyxm_id");//得到党支部委员的ID
			    dZBWY_NAME = request.getParameter("wyxm");//得到党支部委员的姓名。页面要放入名字，逗号隔开
			    String[] arrs_name = null;
			    if(StringUtils.isNotEmpty(dZBWY)) {
					String[] arrs = dZBWY.split(",");
					 arrs_name = dZBWY_NAME.split(",");
					for(int i=0;i<arrs.length;i++) {
						PartyCommitteeMember partyCommitteeMember = new PartyCommitteeMember();
						partyCommitteeMember.setPerentId(zBID);
						partyCommitteeMember.setEmpId(Integer.parseInt(arrs[i]));
						partyCommitteeMember.setEmpName(arrs_name[i]);
						partyCommitteeMember.setDuty("");
						empIds.add(Integer.parseInt(arrs[i]));
						list.add(partyCommitteeMember);
					}
					dzbService.insertwyb(list);
				}
				
				empIds.add(partyBranch.getdZBSJID());
				
				// 保存时，对党支部书记和委员，判断是否在党员信息中，没有，则自动加入党员表
				List<PartyLeagueMember> pList = new ArrayList<>();
				
				if(empIds!=null && empIds.size()>0 && arrs_name != null) {
					for(int i=0;i<empIds.size();i++) {
						
						if (dzbService.seleteDyb(empIds.get(i)).size() == 0) {
							Employee employee = empService.getDmpId(empIds.get(i));
							PartyLeagueMember pMember = new PartyLeagueMember();
							pMember.setgID(partyBranch.getgID());
							pMember.setdZBID(partyBranch.getzBID());
							pMember.setdYLB("2");
							SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
							String formatStr =formatter.format(new Date());
							pMember.setrDRQ(formatStr);
							pMember.setzZRQ(formatStr);
							pMember.setdJZT("1");
							pMember.setEmpId(employee.getEmid());
							pMember.setxM(employee.getXm());
							pMember.setxB(employee.getXb());
							pMember.setgH(employee.getEmid() + "");
							if (null == employee.getSfzh()) {
								pMember.setsFZH("0");
							} else {
								pMember.setsFZH(employee.getSfzh());
							}
							if (null == employee.getCsrq()) {
								pMember.setcSRQ(formatStr);
							} else {
								pMember.setcSRQ(formatter.format(employee.getCsrq()));
							}
							if (null == employee.getMz()) {
								pMember.setmZ("汉");
							} else {
								pMember.setmZ(employee.getMz());
							}
							pMember.setjG(employee.getJg());
							pMember.setjTDZ(employee.getJtdz());
							pMember.setlXDH(employee.getLxdh());
							pMember.setwHCD(employee.getWhcd());
							pMember.setIsStu("0");
							pMember.setStuId(0);
							pMember.setgRJJ("0");
							pMember.setdYLDQK("0");
							pMember.setzZDYQK("0");
							pList.add(pMember);
						}
						
					}
					
					//插入党员
					dzbService.insertDyb(pList);
					
				}
			}
			request.setAttribute("partyBranch", partyBranch);
			request.setAttribute("dZBWY_NAME", dZBWY_NAME);
			String  action = request.getParameter("action");
			if(action.equals("1")) {
				return "zyc/dzb/view";
			} else if(action.equals("2")){
				return "redirect:./add";
			}
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("获得xxxxx信息 addStudentDemo [{}] error," + this.getClass().getName() + "=[{}]",
					this.getClass().getName(), e.getMessage());
			return "error/error";
		}
		return null;
	}
	/**
	 * 跳转到浏览页面
	 * @param request
	 * @return
	 */
	@RequestMapping("view")
	public String view(HttpServletRequest request) {  
		String zBID = request.getParameter("zBID");
		// 获取党支部信息
		PartyBranch partyBranch = dzbService.getDzbById(Integer.parseInt(zBID));
		if(null != partyBranch.getcLRQ()) {
			partyBranch.setcLRQ(partyBranch.getcLRQ().substring(0, partyBranch.getcLRQ().length()-2));
		}
		if(null != partyBranch.getbJJMRQ()) {
			partyBranch.setbJJMRQ(partyBranch.getbJJMRQ().substring(0, partyBranch.getbJJMRQ().length()-2));
		}
		// 获取委员信息(根据党员部id)
		List<PartyCommitteeMember> pList = dzbService.getWylist(Integer.parseInt(zBID));
		String dZBWY_NAME = "";
		for(int i = 0; i < pList.size(); i++) {
			dZBWY_NAME += pList.get(i).getEmpName() +",";
			if(i == pList.size()-1) {
				dZBWY_NAME = dZBWY_NAME.substring(0, dZBWY_NAME.length() -1);
			}
		}
		request.setAttribute("partyBranch", partyBranch);
		request.setAttribute("dZBWY_NAME", dZBWY_NAME);
		return "zyc/dzb/view";
	}
	/**
	 * 跳转到修改页面
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "edit")
	@Token(save = true)
	public String edit(ModelMap model, HttpServletRequest request) {
		try {
			// 获取所以职工信息
			List<Employee> employees = empService.getDmplist();
			request.setAttribute("employees", employees);
			String id = request.getParameter("id");
			// 获取党支部信息(根据党支部id)
			PartyBranch partyBranch = dzbService.getDzbById(Integer.parseInt(id));
			if(null != partyBranch.getcLRQ()) {
				partyBranch.setcLRQ(partyBranch.getcLRQ().substring(0, partyBranch.getcLRQ().length()-2));
			}
			if(null != partyBranch.getbJJMRQ()) {
				partyBranch.setbJJMRQ(partyBranch.getbJJMRQ().substring(0, partyBranch.getbJJMRQ().length()-2));
			}
			request.setAttribute("partyBranch", partyBranch);
			// 获取委员信息(根据党支部id)
			List<PartyCommitteeMember> plList = dzbService.getWylist(Integer.parseInt(id));
			request.setAttribute("plList", plList);
			String dZBWY_NAME = "";
			String dZBWY_ID = "";
			for(int i =0; i < plList.size();i++) {
				dZBWY_NAME += plList.get(i).getEmpName() + ",";
				dZBWY_ID += plList.get(i).getEmpId() + ","; 
			}
			if(!dZBWY_ID.equals("") && !dZBWY_NAME.equals("")) {
				request.setAttribute("dZBWY_NAME", dZBWY_NAME.substring(0, dZBWY_NAME.length()-1));
				request.setAttribute("dZBWY_ID", dZBWY_ID.substring(0,dZBWY_ID.length()-1));
			}
			return "zyc/dzb/edit";	
		} catch (Exception e) {
			LOGGER.error("获得xxxxx信息 addStudentDemoForward [{}] error," + this.getClass().getName() + "=[{}]",
					this.getClass().getName(), e.getMessage());
			return "error/error";
		}
	}
	
	/**
	 * 修改党支部信息
	 * @param model
	 * @param request
	 * @return 
	 */
	@RequestMapping(value = "update")
	public String update(ModelMap model, HttpServletRequest request, PartyBranch partyBranch) {
		String dZBWY_NAME = "";
		String[] arrs_name = null;
		try {
			//修改党支部信息
			partyBranch.setgID("");
			dzbService.updateDzbinfo(partyBranch);
			int zBID = partyBranch.getzBID();
			if (zBID > 0) {
				List<Integer> empIds  = new ArrayList<Integer>();
				//根据党支部ID删除委员（parentId)
			    dzbService.deleteWy(zBID);
				//插入委员信息表
				List<PartyCommitteeMember> list = new ArrayList<PartyCommitteeMember>();
				String dZBWY = request.getParameter("wyxm_id");//得到党支部委员的ID
			    dZBWY_NAME = request.getParameter("wyxm");//得到党支部委员的姓名。页面要放入名字，逗号隔开
				if(StringUtils.isNotEmpty(dZBWY)) {
					String[] arrs = dZBWY.split(",");
					arrs_name = dZBWY_NAME.split(",");
					for(int i=0;i<arrs.length;i++) {
						PartyCommitteeMember partyCommitteeMember = new PartyCommitteeMember();
						partyCommitteeMember.setPerentId(zBID);
						partyCommitteeMember.setEmpId(Integer.parseInt(arrs[i]));
						partyCommitteeMember.setEmpName(arrs_name[i]);
						partyCommitteeMember.setDuty("");
						empIds.add(Integer.parseInt(arrs[i]));
						list.add(partyCommitteeMember);
					}
					dzbService.insertwyb(list);
				}
				
				empIds.add(partyBranch.getdZBSJID());
				
				// 保存时，对党支部书记和委员，判断是否在党员信息中，没有，则自动加入党员表
				List<PartyLeagueMember> pList = new ArrayList<>();
				if(empIds!=null && empIds.size()>0 && arrs_name != null ) {
					for(int i=0;i<empIds.size();i++) {
						if (dzbService.seleteDyb(empIds.get(i)).size() == 0) {
							Employee employee = empService.getDmpId(empIds.get(i));
							PartyLeagueMember pMember = new PartyLeagueMember();
							pMember.setgID(partyBranch.getgID());
							pMember.setdZBID(partyBranch.getzBID());
							pMember.setdYLB("2");
							SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
							String formatStr =formatter.format(new Date());
							pMember.setrDRQ(formatStr);
							pMember.setzZRQ(formatStr);
							pMember.setdJZT("1");
							pMember.setEmpId(employee.getEmid());
							pMember.setxM(employee.getXm());
							pMember.setxB(employee.getXb());
							pMember.setgH(employee.getEmid() + "");
							if (null == employee.getSfzh()) {
								pMember.setsFZH("0");
							} else {
								pMember.setsFZH(employee.getSfzh());
							}
							if (null == employee.getCsrq()) {
								pMember.setcSRQ(formatStr);
							} else {
								pMember.setcSRQ( formatter.format(employee.getCsrq()));
							}
							if (null == employee.getMz()) {
								pMember.setmZ("汉");
							} else {
								pMember.setmZ(employee.getMz());
							}
							pMember.setjG(employee.getJg());
							pMember.setjTDZ(employee.getJtdz());
							pMember.setlXDH(employee.getLxdh());
							pMember.setwHCD(employee.getWhcd());
							pMember.setIsStu("0");
							pMember.setStuId(0);
							pMember.setgRJJ("0");
							pMember.setdYLDQK("0");
							pMember.setzZDYQK("0");
							pList.add(pMember);
						}
						
					}
					
					//插入党员
					if(pList.size() != 0) {
						dzbService.insertDyb(pList);						
					}
					
				}
			}
			request.setAttribute("partyBranch", partyBranch);
			request.setAttribute("dZBWY_NAME", dZBWY_NAME);
			String  action = request.getParameter("action");
			if(action.equals("1")) {
				return "zyc/dzb/view";				
			} else if(action.equals("2")){
				return "redirect:./add";  
			}
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("获得xxxxx信息 addStudentDemo [{}] error," + this.getClass().getName() + "=[{}]",
					this.getClass().getName(), e.getMessage());
			return "error/error";
		}
		return null;
	}
	/**
	 * 获取党支部名称 党支部书记 党支部委员
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("validation")
	@ResponseBody
	public PartyBranch validation(HttpServletRequest request) {
		String dZBMC = request.getParameter("dZBMC");
		String dZBSJXM = request.getParameter("dZBSJXM");
		PartyBranch pBranch = new PartyBranch();
		pBranch.setdZBMC(dZBMC);
		// 查询党支部
		PartyBranch partyBranch = dzbService.selectDzb(pBranch);
		if(null != partyBranch) {
			return partyBranch;			
		}
	    PartyBranch pBranch2 = new PartyBranch();
		pBranch2.setdZBSJXM(dZBSJXM);
		PartyBranch partyBranch2 = dzbService.selectDzb(pBranch2);
		if(null != partyBranch2) {
			return partyBranch2;
		}
		PartyBranch partyBranch3 = new PartyBranch();
		return partyBranch3;
	}

	/**
	 * 删除党支部信息
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "delete", method = RequestMethod.POST)
	public String delete(ModelMap model, HttpServletRequest request) {
		try {
			String[] idList = request.getParameter("idList").split(",");
			List<Integer> list = new ArrayList<>();
			for (int i = 0; i < idList.length; i++) {
				if (dzbService.seletePcmByParentId(Integer.valueOf(idList[i])).size() <= 0) {
					list.add((Integer.valueOf(idList[i])));
				}
			}
			if (list.size() != 0) {
				dzbService.delete(list);
				}
			return "redirect:list";
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("删除 delete [{}] error," + this.getClass().getName() + "=[{}]", this.getClass().getName(),
					e.getMessage());
			return "error/error";
		}
	}

	/**
	 * @param request
	 * @return
	 */
	@RequestMapping("validation_delete")
	@ResponseBody
	public List<Integer> validation_delete(HttpServletRequest request) {
		String[] idList = request.getParameter("idList").split(",");
		List<Integer> list = new ArrayList<>();
		for (int i = 0; i < idList.length; i++) {
			if (dzbService.seletePcmByParentId(Integer.valueOf(idList[i])).size() > 0) {
				list.add((Integer.valueOf(idList[i])));
			}
		}
		return list;
	}

	/**
	 * xxxxx下载
	 * 
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "export_dzb")
	public @ResponseBody void export_dzb(HttpServletRequest request, HttpServletResponse response) throws Exception {
		try {
			String dzbmc = "";
			if (null != request.getParameter("dZBMC")) {
				dzbmc = request.getParameter("dZBMC");
			}
			PartyBranch partyBranch = new PartyBranch();
			partyBranch.setdZBMC(dzbmc);
			List<PartyBranch> datalist = dzbService.getDzbList(partyBranch);
			String[][] title_name = { { "党支部id", "党支部名称", "党支部书记", "成立时间", "本届届满时间", "备注" } };
			String[] title_style = { "hwzs_16_bold_25", "hwzs_16_bold_25", "kt_12_bold_18", "st_12_r_20", "st_12_n_20",
					"st_12_n_20" };
			String fileName = "党支部信息";
			String[] remark = { "" };
			List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			if (datalist != null && !datalist.isEmpty()) {
				for (PartyBranch res : datalist) {
					Map<String, Object> map = new LinkedHashMap<String, Object>();
					if(null != res.getcLRQ()) {
						res.setcLRQ(res.getcLRQ().substring(0, 19));
					}
					if(null != res.getbJJMRQ()) {
						res.setbJJMRQ(res.getbJJMRQ().substring(0, 19));
					}
					map.put("zBID", res.getzBID());
					map.put("dZBMC", res.getdZBMC());
					map.put("dZBSJXM", res.getdZBSJXM());
					map.put("cLRQ", res.getcLRQ());
					map.put("bJJMRQ", res.getbJJMRQ());
					map.put("remark", res.getRemark());
					list.add(map);
				}
			}
			HSSFWorkbook wb = ExpExcelUtil.getWorkBookExcel(title_name, title_style, 100, remark, fileName, list);
			try {
				String filenameConvert = "党支部信息";/* new String(fileName.getBytes("GB2312"), "ISO8859-1"); */
				response.reset();
				response.setContentType("application/vnd.ms-excel;charset=utf-8");
				response.setHeader("Content-Disposition",
						"attachment;filename=" + new String((filenameConvert + ".xls").getBytes(), "iso-8859-1"));
				response.setDateHeader("Expires", 0);
				ServletOutputStream os = response.getOutputStream();
				wb.write(os);
				os.flush();
			} catch (Exception e) {
				System.out.println("网络连接断开，可能用户取消了导出");
			}
		} catch (RPCException e) {
			LOGGER.error("获得xxxxx信息 exportStudentjobList [{}] error," + this.getClass().getName() + "=[{}]",
					this.getClass().getName(), e.getMessage());
		}
	}
	
	
	@InitBinder  
	public void initBinder(WebDataBinder binder) {  
	    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
	    dateFormat.setLenient(false);  
	    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));  
	}
	
	

}
